package com.zsl.swing.redis.desktop.model;

import com.zsl.swing.redis.desktop.utils.CollectionUtils;
import com.zsl.swing.redis.desktop.utils.StringUtils;

import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class DbCountConfigEntity {

    private static final String DB_DELIMITER  =",";

    private static final String INDEX_NAME_DELIMITER = "@";

    private static final String NEW_LINE = "\n";

    private String dbShowConfig;

    private String uniqueId;

    private String showName;

    public static DbCountConfigEntity defaultConfig(NodeEntity nodeEntity){
        DbCountConfigEntity configEntity = new DbCountConfigEntity();

        configEntity.setUniqueId(nodeEntity.getUniqueId());
        configEntity.setShowName(nodeEntity.getShowName());

        configEntity.setDbShowConfig( buildDefaultDbShowConfig());
        return configEntity;
    }

    public String getUniqueId() {
        return uniqueId;
    }

    public void setUniqueId(String uniqueId) {
        this.uniqueId = uniqueId;
    }


    public String getDbShowConfig(){
        return !StringUtils.isEmpty(this.dbShowConfig)? this.dbShowConfig :  buildDefaultDbShowConfig();
    }

    private static String buildDefaultDbShowConfig(){
        return IntStream.range(0, 8).boxed().map(o -> o + INDEX_NAME_DELIMITER + o).collect(Collectors.joining(DB_DELIMITER + NEW_LINE));

    }

    public String getShowName() {
        return showName;
    }

    public void setShowName(String showName) {
        this.showName = showName;
    }

    public void setDbShowConfig(String dbShowConfig){
        this.dbShowConfig = dbShowConfig;
    }

    public TreeMap<Integer,String> getDbShowConfigMap(){
        String config = this.getDbShowConfig();

        System.out.println("当前配置：" + config);

        TreeMap<Integer, String> targetMap = null;
        try{
            targetMap = this.parseDbShowConfigToMap(config);
        }catch (Exception e){
            System.out.println("当前库配置有误，启用默认配置");
        }

        if(CollectionUtils.isEmpty(targetMap)){
            targetMap = this.parseDbShowConfigToMap(buildDefaultDbShowConfig());
        }

        return targetMap;

    }

    private TreeMap<Integer, String> parseDbShowConfigToMap(String config) {

        config = config.replaceAll("\\s", "");

        String[] split = config.split(DB_DELIMITER);

        TreeMap<Integer, String> map = new TreeMap<>();
        for (String item : split) {

            if(!StringUtils.isEmpty(item)){
                String[] indexNameArray = item.split(INDEX_NAME_DELIMITER);

                map.put(Integer.parseInt(indexNameArray[0]), indexNameArray[1]);
            }

        }

        return map;
    }

}
